package com.hmall.common.config;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.amqp.core.Message;
import com.hmall.common.utils.UserContext;

public class UserContextAdvice implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object[] args = invocation.getArguments();
        try {
            for (Object arg : args) {
                if (arg instanceof Message) {
                    Message message = (Message) arg;
                    Long userId = (Long) message.getMessageProperties().getHeaders().get("user-info");
                    if (userId != null) {
                        UserContext.setUser(userId);
                    }
                    break;
                }
            }
            return invocation.proceed();
        } finally {
            UserContext.removeUser();
        }
    }
}
